package com.huiyin.ui.moments;

import java.io.File;
import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.MomentsCircleItem;
import com.huiyin.bean.MomentsCircleListBean;
import com.huiyin.bean.MomentsPublishParams;
import com.huiyin.ui.MainActivity;
import com.huiyin.ui.moments.adapter.MomentsPictureGridViewAdapter;
import com.huiyin.ui.moments.view.MomentsCircleListDialog;
import com.huiyin.ui.moments.view.MomentsCircleListDialog.SelectCircleListener;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.DialogUtil;
import com.huiyin.utils.FileUtils;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.UPYunUploadUtil;
import com.huiyin.utils.UPYunUploadUtil.UploadListener;
import com.huiyin.utils.imageupload.ImageFolder;
import com.huiyin.wight.MyGridView;
import com.huiyin.wight.Tip;

/**
 * 秀图片
 * 
 * @author zhyao
 * 
 */
public class MomentsShowPictureActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "MomentsShowPictureActivity";

	/** 相册 **/
	private static final int REQUEST_CODE_PICK_IMAGE = 0;

	/** 照相 **/
	private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1;

	/** 返回 **/
	private TextView mBackTv;

	/** 发布 **/
	private TextView mPublishTv;

	/** 标题输入框 **/
	private EditText mTitleEdt;

	/** 内容输入框 **/
	private EditText mContentEdt;

	/** 选择图片九宫格 **/
	private MyGridView mPicGridView;

	/** 添加图片按钮 **/
	private Button mAddPicBtn;

	/** 选择圈子布局 **/
	private RelativeLayout mSelectCircleLayout;

	/** 选择圈子信息 **/
	private TextView mSelectCircleTv;

	/** 选择图片九宫格adapter **/
	private MomentsPictureGridViewAdapter mPicGridAdapter;

	/** 照相机拍照保存的路径 **/
	private String mCameraCapturePath = null;

	/** 圈子列表选择对话框 **/
	private MomentsCircleListDialog mCircleListDialog;
	
	/**上传又拍云返回的图片地址**/
	private ArrayList<String> mUpYunBackUrlList;

	/** 选择的圈子ID **/
	private String selectCircleId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_moments_show_picture);

		initView();
		initData();
	}

	private void initView() {
		mBackTv = (TextView) findViewById(R.id.tv_back);
		mPublishTv = (TextView) findViewById(R.id.tv_publish);
		mTitleEdt = (EditText) findViewById(R.id.edt_title);
		mContentEdt = (EditText) findViewById(R.id.edt_content);
		mPicGridView = (MyGridView) findViewById(R.id.grv_pic_selected);
		mAddPicBtn = (Button) findViewById(R.id.btn_add_pic);
		mSelectCircleLayout = (RelativeLayout) findViewById(R.id.rl_select_circle);
		mSelectCircleTv = (TextView) findViewById(R.id.tv_circle_select);

		mBackTv.setOnClickListener(this);
		mPublishTv.setOnClickListener(this);
		mAddPicBtn.setOnClickListener(this);
		mSelectCircleLayout.setOnClickListener(this);
	}

	private void initData() {
		mPicGridAdapter = new MomentsPictureGridViewAdapter(this);
		mPicGridView.setAdapter(mPicGridAdapter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 返回
		case R.id.tv_back:
			AppManager.getAppManager().finishActivity();
			break;
		// 发布
		case R.id.tv_publish:
			if (check()) {
				uploadPictures();
			}

			break;
		// 添加图片
		case R.id.btn_add_pic:
			if(mPicGridAdapter.getImagePathList().size() < 6) {
				showPictureSelectDialog();
			}
			else {
				UIHelper.showToast("最多选择6张图片");
			}
			break;
		// 选择圈子
		case R.id.rl_select_circle:
			requestCircleList();
			break;

		default:
			break;
		}
	}

	/**
	 * 选择图片的方式对话框
	 */
	private void showPictureSelectDialog() {

		if (mPicGridAdapter.getImagePathList().size() > 6) {
			UIHelper.showToast("最多上传6张图片");
			return;
		}

		DialogUtil.showPictureSelectDialog(mContext, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				// 相册
				case 0:
					getImageFromAlbum();
					break;
				// 照相
				case 1:
					getImageFromCamera();
					break;

				default:
					break;
				}
			}
		});

	}

	/**
	 * 选择圈子列表对话框
	 */
	private void showCircleListDialog(ArrayList<MomentsCircleItem> circleList) {
		mCircleListDialog = new MomentsCircleListDialog(this, circleList, selectCircleId, new SelectCircleListener() {

			@Override
			public void onSelect(MomentsCircleItem circleItem) {
				try {
					showCircleInfo(circleItem);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		mCircleListDialog.show();
	}

	/**
	 * 显示选择的圈子信息
	 */
	private void showCircleInfo(MomentsCircleItem circleItem) {
		mSelectCircleTv.setText(circleItem.getNAME());
		selectCircleId = circleItem.getID();
	}
	
	/**
	 * 相册获取图片
	 */
	private void getImageFromAlbum() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");// 相片类型
		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
	}

	/**
	 * 拍照获取图片
	 */
	private void getImageFromCamera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
			mCameraCapturePath = ImageFolder.getTempImageName().getPath();
			getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraCapturePath)));
			startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
		} else {
			UIHelper.showToast("请确认已经插入SD卡");
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 相册
		if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) {
			if (data == null || "".equals(data)) {
				// 相册没有图片
				UIHelper.showToast("没有选择图片");
				return;
			}
			Uri selectedImage = FileUtils.geturi(data, this);
			String[] filePathColumns = { MediaStore.Images.Media.DATA };
			Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
			if(c != null) {
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				String picturePath = c.getString(columnIndex);
				c.close();
				mPicGridAdapter.addImagePath(picturePath);
			}
		}

		// 照相机
		else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && resultCode == RESULT_OK) {
			if (data == null || "".equals(data)) {
				File f = new File(mCameraCapturePath);
				if (!f.exists()) {
					return;
				} else {
					mPicGridAdapter.addImagePath(mCameraCapturePath);
					return;
				}
			}
		}

		super.onActivityResult(requestCode, resultCode, data);

	}
	
	/**
	 * 上传图片
	 */
	private void uploadPictures() {
		Tip.showLoadDialog(this, getString(R.string.loading));

		final ArrayList<String> mImagePathList = mPicGridAdapter.getImagePathList();
		mUpYunBackUrlList = new ArrayList<String>();

		for (String filePath : mImagePathList) {
			UPYunUploadUtil mUploadUtil = new UPYunUploadUtil(this);
			mUploadUtil.uploadFile(filePath, new UploadListener() {

				@Override
				public void onSuccess(String upYunBackUrl) {
					Log.d(TAG, "uploadPictures onSuccess　: upYunBackUrl = " + upYunBackUrl);
					mUpYunBackUrlList.add(upYunBackUrl);


					//所有图片上传完成
					if(mUpYunBackUrlList.size() == mImagePathList.size()) {
						Tip.colesLoadDialog();
						//发布
						publishRequest();
					}

				}

				@Override
				public void onFail() {
					Tip.colesLoadDialog();
					UIHelper.showToast("上传图片失败");
					return;
				}
			});
		}

	}
	
	 /**
     * 发布请求
     */
	private void publishRequest() {
		
		StringBuffer imgBuffer = new StringBuffer();
		for (int i = 0; i < mUpYunBackUrlList.size(); i++) {
			imgBuffer.append(mUpYunBackUrlList.get(i));
			if(i < mUpYunBackUrlList.size() - 1) {
				imgBuffer.append(",");
			}
		}
		
		MomentsPublishParams params = new MomentsPublishParams();
		params.setType("1");//秀图
		params.setTitle(mTitleEdt.getText().toString().trim());
		params.setContent(mContentEdt.getText().toString().trim());
		params.setSpotlight_circle_id(selectCircleId);
		params.setUser_id(AppContext.getInstance().userId);
		params.setShow_img(imgBuffer.toString());
		params.setOrigin("3");

		RequstClient.showPublish(params, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				
				int type = JSONParseUtils.getInt(content, "type");
				String msg = JSONParseUtils.getString(content, "msg");
				UIHelper.showToast(msg);
				// 成功
				if(type == 1) {
					Intent intent = new Intent();
					AppContext.MAIN_TASK = AppContext.MOMENTS;
					intent.setClass(MomentsShowPictureActivity.this, MainActivity.class);
					intent.putExtra(MainActivity.IS_REFRESH_MOMENTS, true);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
				
				
			}
		});
	
	}

	/**
	 * 获取圈子列表
	 */
	private void requestCircleList() {
		RequstClient.circleList(new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				MomentsCircleListBean bean = MomentsCircleListBean
						.explainJson(content, MomentsShowPictureActivity.this);

				if(bean.type == 1) {
					showCircleListDialog(bean.getCircleList());
				}
				else {
					UIHelper.showToast(bean.msg);
				}

			}
		});
	}

	/**
	 * 检验是否符合发布条件
	 * 
	 * @return
	 */
	private boolean check() {

		String titleStr = mTitleEdt.getText().toString().trim();
		String contentStr = mContentEdt.getText().toString().trim();

		if (TextUtils.isEmpty(titleStr)) {
			UIHelper.showToast("请输入标题");
			return false;
		}

		if (titleStr.length() < 5 || titleStr.length() > 20) {
			UIHelper.showToast("输入的标题在5到20字范围");
			return false;
		}

		if (TextUtils.isEmpty(contentStr)) {
			UIHelper.showToast("请输入您要分享的内容");
			return false;
		}

		if (contentStr.length() < 8 || contentStr.length() > 1000) {
			UIHelper.showToast("分享的内容在8到1000字范围");
			return false;
		}

		if (mPicGridAdapter.getImagePathList().size() == 0) {
			UIHelper.showToast("至少选择一张图片");
			return false;
		}

		if (StringUtils.isEmpty(selectCircleId)) {
			UIHelper.showToast("请选择您要发布的圈子");
			return false;
		}

		return true;
	}
}
